package com.fauks.ssm.springdata.jpa;

import com.fauks.ssm.entity.Customer;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 * 基本操作测试
 */
public class BasicTest {
    public static void main(String[] args) {
        testSave();
        //testUpdate();
        //testFind();
        //testGetReference();
        //testDelete();
    }

    //添加数据
    private static void testSave() {
        //加载配置文件创建工厂（实体管理器工厂）
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("testJpa");
        //获取实体管理独享
        EntityManager entityManager = factory.createEntityManager();
        //获取事务对象，并开启s事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //保存实体
        Customer customer = new Customer();
        customer.setCustName("Fauks教育");
        customer.setCustIndustry("教育");
        entityManager.persist(customer);
        //提交事务
        transaction.commit();
        //释放资源
        entityManager.close();
        factory.close();
    }

    //查询数据
    private static void testFind() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        Customer customer = entityManager.find(Customer.class, 1L);
        //System.out.println(customer);
        transaction.commit();
        entityManager.close();
    }

    //查询：懒加载
    private static void testGetReference() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        Customer customer = entityManager.getReference(Customer.class, 1L);
        System.out.println(customer);
        transaction.commit();
        entityManager.close();
    }

    //修改数据
    private static void testUpdate() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        Customer customer = entityManager.getReference(Customer.class, 1L);
        customer.setCustId(1L);
        customer.setCustName("Fauk多多拼");
        entityManager.merge(customer);
        transaction.commit();
        entityManager.close();
    }

    //删除数据
    private static void testDelete() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        Customer customer = entityManager.getReference(Customer.class, 4L);
        entityManager.remove(customer);
        transaction.commit();
        entityManager.close();
    }

}
